<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组扁平化</title>
</head>

<body>

</body>

</html>
<script>
    var arr = [1, [2, [3, 4, 5]], 6]

    //方法一：flat
    var new_arr = arr.flat(3) //该方法返回
    console.log(new_arr)

    //方法二闭包递归：
    var fnc = (function() {
        var new_arr2 = [];

        return function fn(arr) {
            for (let i = 0; i < arr.length; i++) {
                if (Array.isArray(arr[i])) {
                    fn(arr[i])
                } else {
                    new_arr2.push(arr[i])
                }
            }
            return new_arr2
        }

    })()

    var new_arr2 = fnc(arr);
    console.log(new_arr2) //[1, 2, 3, 4, 5, 6]

    //方法三:reduce递归
    var flatten = arr => {
        return arr.reduce((pre, cur) => {
            return pre.concat(Array.isArray(cur) ? flatten(cur) : cur)
        }, [])
    }

    var new_arr3 = flatten(arr);
    console.log(new_arr3) //[1, 2, 3, 4, 5, 6]

    //方法四，字符串法
    var arr_str = arr.toString().split(',')
    console.log(arr_str) //["1", "2", "3", "4", "5", "6"]
    console.log(arr_str.map(item => {
            return Number(item)
        })) //[1, 2, 3, 4, 5, 6]

    //方法五升级版，JSON.stringify
    var arr5 = JSON.parse('[' + JSON.stringify(arr).replace(/\[|\]/g, '') + ']')
    console.log(arr5) //[1, 2, 3, 4, 5, 6]
</script>